#include<iostream>
#include<string>
#include<string.h>
#include <unordered_map>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sstream>

using namespace std;

const int PORT = 8081;

int main() {
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    char buffer[1024];

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    // 绑定地址和端口
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind");
        exit(1);
    }

    // 监听连接
    if (listen(server_fd, 5) == -1) {
        perror("listen");
        exit(1);
    }

    while (true) {
        // 接受客户端连接
        if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len)) == -1) {
            perror("accept");
            exit(1);
        }

        // 读取客户端发送的数据
        read(client_fd, buffer, sizeof(buffer));
        cout << "Received: "<< buffer<< endl;

        // 解析客户端发送的数据
        // 读取客户端发送的数据


        // 解析客户端发送的数据
        stringstream ss(buffer);
        string username, password;

        getline(ss, username, ' ');
        getline(ss, password, ' ');
        cout<< username<< endl<< password<< endl;

// 验证登录
        unordered_map<string, string> users;
        users["user1"] = "password1";
        users["user2"] = "password2";
        users["user3"] = "password3";
        if (users[username] == password) {
            send(client_fd, "Login successful", 17, 0);
            // 死循环，继续与客户端通信
//            while (1) {
//                // 读取客户端发送的数据
//                read(client_fd, buffer, sizeof(buffer));
//                cout << "Received: "<< buffer<< endl;
//
//                // 将客户端发送的数据发送回去
//                send(client_fd, buffer, strlen(buffer), 0);
                while (1) {
                    // 读取客户端发送的数据
                    char inbuff[1024];
                    read(client_fd, inbuff, sizeof(inbuff));
                    cout << "Received: "<< inbuff<< endl;

                    // 将客户端发送的数据发送回去
                    send(client_fd, inbuff, strlen(buffer), 0);
            }
        } else {
            send(client_fd, "Login failed", 13, 0);
        }


    }
    // 关闭与客户端的连接
    close(client_fd);
    // 关闭套接字
    close(server_fd);

    return 0;
}